package com.fafu.service.Impl;

import com.fafu.dao.mapper.ManagerMapper;
import com.fafu.dao.mapper.StudentMapper;
import com.fafu.model.Manager;
import com.fafu.model.Student;
import com.fafu.pojo.ManagerInfoPojo;
import com.fafu.pojo.ManagerListPojo;
import com.fafu.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import util.*;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

import static util.Dictionary.CODE.IDEN_ERROR;
import static util.Dictionary.CODE.PASSWORD_ERROR;
import static util.Dictionary.CODE.SUCCESS;
import static util.Dictionary.LOGIN.*;
import static util.Dictionary.LOGIN.USER_TYPE_MANAGER;
import static util.Dictionary.LOGIN.USER_TYPE_STUDENT;
import static util.Dictionary.MANAGER.MANAGER_NOT_USER;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private JedisTool jedisTool;
    @Override
    public Map<String,Object> loggin(Map<String, Object> paramMap) {
        Integer type = (Integer) paramMap.get("type");
        Map<String,Object> reMap = new HashMap<>();
        String iden = (String) paramMap.get("iden");
        String pwd = (String) paramMap.get("password");
        HttpServletResponse response = (HttpServletResponse) paramMap.get("response");
        switch (type){
            case USER_TYPE_STUDENT : reMap = studentLoggin(iden,pwd,response);break;
            case USER_TYPE_MANAGER : reMap = managerLoggin(iden,pwd,response);break;
            default: reMap.put("code",Dictionary.CODE.NOT_KOWN_ERROR);
                      reMap.put("msg","未知错误");
        }
        return reMap;
    }

    @Override
    public Map<String, Object> loggout(HttpServletRequest request,HttpServletResponse response) {
        /**
         * 查询token,删除redis,删除cookie
         */
        String key = CookieUtils.getCookie(request,LOGIN_TOKEN_NAME);
//        jedisTool.set4Value(key,"-1",0L);
        jedisTool.deletKey(key);
        CookieUtils.deletCookie(response,LOGIN_TOKEN_NAME);
        return null;
    }

    @Override
    public Map<String, Object> pwdChange(Map<String, Object> paramMap) {
        Integer id = (Integer) paramMap.get("id");
        String old = (String) paramMap.get("oldPassword");
        String pwd = (String) paramMap.get("password");
        Integer type = (Integer)paramMap.get("type");
        HttpServletRequest request = (HttpServletRequest) paramMap.get("request");
        HttpServletResponse response = (HttpServletResponse) paramMap.get("response");
        Map<String,Object> reMap = new HashMap<>();
        switch (type){
            case USER_TYPE_STUDENT : reMap = studentPwdChange(id,old,pwd);break;
            case USER_TYPE_MANAGER : reMap = managerPwdChange(id,old,pwd);break;
            default: reMap.put("code",Dictionary.CODE.NOT_KOWN_ERROR);
                reMap.put("msg","未知错误");
        }
        Integer code = (Integer) reMap.get("code");
        if (code.equals(SUCCESS))
            loggout(request,response);
        return reMap;
    }

    @Override
    public Map<String, Object> getUserId(HttpServletRequest request) {
        String token = CookieUtils.getCookie(request,LOGIN_TOKEN_NAME);
        if(token == null){
            return new MyMap().put("data","-1").toMap();
        }
        String idStr = jedisTool.getValue(token);
        String[] ids = idStr.split("\\.");
        return new MyMap().put("data",ids[1]).toMap();
    }
    @Override
    public Map<String, Object> getUserIdStr(HttpServletRequest request) {
        String token = CookieUtils.getCookie(request,LOGIN_TOKEN_NAME);
        if(token == null){
            return new MyMap().put("data","-1").toMap();
        }
        String idStr = jedisTool.getValue(token);
        return new MyMap().put("data",idStr).toMap();
    }
    @Override
    public Map<String, Object> addUser(HttpServletRequest request, Map<String, Object> paramMap) {
        Manager manager = (Manager) paramMap.get("manager");
        Example example = new Example(Manager.class);
        example.and().andEqualTo("identity",manager.getIdentity());
        List<Manager> relist = managerMapper.selectByExample(example);
        if(relist != null)
            return new MyMap().put("code", Dictionary.CODE.IDEN_EXPIRED).put("msg","账号已存在").toMap();

        String pwd = "666666";
        String salt = MD5Utils.createSalt();
        pwd = MD5Utils.passwordAddSalt(pwd,salt);
        manager.setSalt(salt);
        manager.setPassword(pwd);
        manager.setAddTime(System.currentTimeMillis());
        manager.setIsUsed(Dictionary.MANAGER.MANAGER_IS_USER);
//        managerMapper.updateByPrimaryKey(manager);
        managerMapper.insertSelective(manager);
        return new MyMap().put("code",SUCCESS).toMap();
    }

    @Override
    public Map<String, Object> deleteUser(Map<String, Object> paramMap) {
        Integer id = (Integer) paramMap.get("id");
        Manager manager = managerMapper.selectByPrimaryKey(id);
        manager.setIsUsed(MANAGER_NOT_USER);
        managerMapper.updateByPrimaryKeySelective(manager);
        return null;
    }

    @Override
    public Map<String,Object> getUserInfo(Integer id){
        ManagerInfoPojo managerInfoPojo = managerMapper.searchInfoEx(new MyMap().put("id",id).toMap());
        managerInfoPojo.setPassword(null);
        managerInfoPojo.setSalt(null);
        Integer isuser = managerInfoPojo.getIsUsed();
        if(isuser == null ||isuser.equals(Dictionary.MANAGER.MANAGER_NOT_USER))
            managerInfoPojo.setIsUsedName("否");
        else
            managerInfoPojo.setIsUsedName("是");
        return new MyMap().put("data",managerInfoPojo).toMap();
    }

    @Override
    public Map<String,Object> searchManagerList(Map<String,Object> paramMap) {
        PageHelper.startPage((Integer)paramMap.get("pageNum"),(Integer)paramMap.get("pageSize"));
        List list = managerMapper.searchManagerList();
        PageInfo pageInfo = new PageInfo(list);
        return new MyMap().put("data",pageInfo.getList()).put("count",pageInfo.getTotal()).toMap();
    }

    @Override
    public Manager getUserInfoModel(Integer id) {
        return managerMapper.selectByPrimaryKey(id);
    }

    private Map<String,Object> studentLoggin(String iden, String pwd, HttpServletResponse response){
        Example example = new Example(Student.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("studentIden",iden);
        List<Student> studentList = studentMapper.selectByExample(example);
        if(studentList == null || studentList.size() == 0)
           return new MyMap()
                   .put("code", IDEN_ERROR)
                   .put("msg","账号不存在").toMap();
        String salt = studentList.get(0).getSalt();
        if(MD5Utils.passwordAddSalt(pwd,salt).equals(studentList.get(0).getPassword())){//登陆成功
            /**
             * 生成token
             * 写入cookie
             * 写入redis
             * 返回成功
             */
            String token = TokenUtil.createToken();
            CookieUtils.writeCookie(response,LOGIN_TOKEN_NAME,token);
            jedisTool.set4Value(token,"student."+studentList.get(0).getId().toString());
            return new MyMap()
                    .put("code", SUCCESS)
                    .put("data", studentList.get(0).getId()).toMap();
        }
        return new MyMap().put("code", PASSWORD_ERROR).put("msg","密码错误").toMap();
    }

    private Map<String,Object> managerLoggin(String iden, String pwd, HttpServletResponse response){
        Example example = new Example(Manager.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("identity",iden);
        List<Manager> managerList = managerMapper.selectByExample(example);
        if(managerList == null || managerList.size() == 0)
            return new MyMap()
                    .put("code", IDEN_ERROR)
                    .put("msg","账号不存在").toMap();
        String salt = managerList.get(0).getSalt();
        if(MD5Utils.passwordAddSalt(pwd,salt).equals(managerList.get(0).getPassword())){//登陆成功
            /**
             * 生成token
             * 写入cookie
             * 写入redis
             * 返回成功
             */
            String token = TokenUtil.createToken();
            CookieUtils.writeCookie(response,LOGIN_TOKEN_NAME,token);
            jedisTool.set4Value(token,"manager."+managerList.get(0).getId().toString());
            return new MyMap()
                    .put("code", SUCCESS)
                    .put("data", managerList.get(0).getId()).toMap();
        }
        return new MyMap().put("code", PASSWORD_ERROR).put("msg","密码错误").toMap();

    }

    private Map<String,Object> managerPwdChange(Integer id,String old, String pwd){
        Manager manager = managerMapper.selectByPrimaryKey(id);
        String salt = manager.getSalt();
        if(!MD5Utils.passwordAddSalt(old,salt).equals(manager.getPassword()))
            return new MyMap().put("code", PASSWORD_ERROR).put("msg","密码错误").toMap();
        salt = MD5Utils.createSalt();
        manager.setSalt(salt);
        manager.setPassword(MD5Utils.passwordAddSalt(pwd,salt));
        managerMapper.updateByPrimaryKey(manager);
        return new MyMap().put("code", SUCCESS).toMap();
    }
    private Map<String,Object> studentPwdChange(Integer id,String old, String pwd){
        Student student = studentMapper.selectByPrimaryKey(id);
        String salt = student.getSalt();
        if(!MD5Utils.passwordAddSalt(old,salt).equals(student.getPassword()))
            return new MyMap().put("code", PASSWORD_ERROR).put("msg","密码错误").toMap();
        salt = MD5Utils.createSalt();
        student.setSalt(salt);
        student.setPassword(MD5Utils.passwordAddSalt(pwd,salt));
        studentMapper.updateByPrimaryKey(student);
        return new MyMap().put("code", SUCCESS).toMap();
    }
}
